package com.uh.microservice.core.util;

import com.github.yitter.idgen.YitIdHelper;
import com.uh.microservice.core.CONSTANTS;
import com.uh.microservice.core.spring.mvc.ThreadVariable;
import org.apache.commons.lang.StringUtils;

import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by liming on 2017/9/18.
 */
public class DataPreset {
    private static DataPreset instance=null;

    public static synchronized DataPreset getInstance(){
        if(instance==null)
            instance = new DataPreset();

        return instance;
    }

    public Map insertPre(Map entity){
        try{
            Object create_time=entity.get(CONSTANTS.C_CRT_TIME);
            if(create_time==null)
                entity.put(CONSTANTS.C_CRT_TIME,new Date());

            String ip=(String)ThreadVariable.getInstance().get(CONSTANTS.REQ_IP);
            entity.put(CONSTANTS.C_CRT_IP,ip);

            Map uinfo=(Map)ThreadVariable.getInstance().get(CONSTANTS.REQ_UKEY);
            //添加对收费员的支持
            if(uinfo==null) uinfo=(Map)ThreadVariable.getInstance().get(CONSTANTS.REQ_CKEY);
            if(uinfo!=null){
                String id=(String)uinfo.get("ID");
                entity.put(CONSTANTS.C_CRT_ID,id);
            }

            //String idx=(String)entity.get(CONSTANTS.C_PK);
            //if(StringUtils.isBlank(idx))
                entity.put(CONSTANTS.C_PK,crtKey());

        }catch(Exception e){
            e.printStackTrace();
        }
        return entity;
    }

    public Map updatePre(Map entity){
        try{
            Object update_time=entity.get(CONSTANTS.C_UPT_TIME);
            if(update_time==null)
                entity.put(CONSTANTS.C_UPT_TIME,new Date());

            String ip=(String)ThreadVariable.getInstance().get(CONSTANTS.REQ_IP);
            entity.put(CONSTANTS.C_UPT_IP,ip);

            Map uinfo=(Map)ThreadVariable.getInstance().get(CONSTANTS.REQ_UKEY);
            //添加对收费员的支持
            if(uinfo==null) uinfo=(Map)ThreadVariable.getInstance().get(CONSTANTS.REQ_CKEY);
            if(uinfo!=null){
                String id=(String)uinfo.get("ID");
                entity.put(CONSTANTS.C_UPT_ID,id);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return entity;
    }

    public Long crtKey(){
        Long id= YitIdHelper.nextId();
        return id;
        //return UUID.randomUUID().toString();
    }

    public Map qryParm(Map param){
        if(param==null) param=new HashMap();
        Map loginInfo = (Map) ThreadVariable.getInstance().get(CONSTANTS.REQ_UKEY);
        if(loginInfo !=null && loginInfo.containsKey("ID")){
            param.put(CONSTANTS.LOGIN_USER_ID,loginInfo.get("ID"));
        }
        return param;
    }
}

